const { pool } = require('../config/db');
const { ValidationError, NotFoundError } = require('../middleware/error');
const CartModel = require('./cart.model');
const ProductModel = require('./product.model');

class OrderModel {
  // 生成订单号
  static generateOrderNumber() {
    const date = new Date();
    const year = date.getFullYear().toString().slice(-2);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `ORD${year}${month}${day}${random}`;
  }

  // 创建订单
  static async createOrder(userId, orderData) {
    console.log(`[OrderModel.createOrder] Creating order for userId: ${userId}`);
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 获取收货地址信息
      const [addresses] = await connection.execute(
        'SELECT * FROM user_addresses WHERE id = ? AND user_id = ?',
        [orderData.shipping_address_id, userId]
      );

      if (addresses.length === 0) {
        throw new ValidationError('收货地址不存在或不属于当前用户');
      }

      const address = addresses[0];

      // 生成订单号
      const orderNumber = this.generateOrderNumber();

      // 插入订单主表
      const [orderResult] = await connection.execute(
        `INSERT INTO orders (
          user_id, 
          order_number, 
          total_amount, 
          status, 
          shipping_address_id,
          shipping_recipient_name,
          shipping_phone_number,
          shipping_street_address,
          shipping_city,
          shipping_district,
          shipping_province,
          shipping_postal_code,
          shipping_country,
          customer_remarks,
          created_at,
          updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
        [
          userId,
          orderNumber,
          orderData.total_amount,
          'pending_payment',
          address.id,
          address.recipient_name,
          address.phone_number,
          address.street_address,
          address.city,
          address.district,
          address.province,
          address.postal_code,
          address.country,
          orderData.customer_remarks || null
        ]
      );

      const orderId = orderResult.insertId;

      // 插入订单项
      for (const item of orderData.items) {
        await connection.execute(
          `INSERT INTO order_items (
            order_id,
            product_id,
            product_name_at_purchase,
            price_at_purchase,
            quantity,
            subtotal,
            created_at
          ) VALUES (?, ?, ?, ?, ?, ?, NOW())`,
          [
            orderId,
            item.product_id,
            item.product_name,
            item.price,
            item.quantity,
            item.price * item.quantity
          ]
        );
      }

      // 清空购物车
      await connection.execute(
        'DELETE FROM cart_items WHERE user_id = ?',
        [userId]
      );

      await connection.commit();

      // 获取新创建的订单信息
      const [order] = await connection.execute(
        `SELECT o.*, 
          sa.recipient_name, sa.phone_number, sa.street_address, 
          sa.city, sa.district, sa.province, sa.postal_code, sa.country
        FROM orders o
        LEFT JOIN user_addresses sa ON o.shipping_address_id = sa.id
        WHERE o.id = ?`,
        [orderId]
      );

      return order[0];
    } catch (error) {
      await connection.rollback();
      console.error(`[OrderModel.createOrder] Error creating order for userId: ${userId}:`, error);
      throw error;
    } finally {
      connection.release();
    }
  }

  // 获取用户订单列表
  static async getUserOrders(userId, params = {}) {
    console.log(`[OrderModel.getUserOrders] Fetching orders for userId: ${userId}`);
    try {
      const { page = 1, limit = 10, status = null } = params;
      const offset = (page - 1) * limit;

      let query = `
        SELECT o.*, 
          sa.recipient_name, sa.phone_number, sa.street_address, 
          sa.city, sa.district, sa.province, sa.postal_code, sa.country
        FROM orders o
        LEFT JOIN user_addresses sa ON o.shipping_address_id = sa.id
        WHERE o.user_id = ?
      `;
      const queryParams = [parseInt(userId)];

      if (status) {
        query += ' AND o.status = ?';
        queryParams.push(status);
      }

      query += ' ORDER BY o.created_at DESC LIMIT ? OFFSET ?';
      queryParams.push(parseInt(limit), parseInt(offset));

      const [orders] = await pool.query(query, queryParams);

      // 获取总记录数
      let countQuery = 'SELECT COUNT(*) as total FROM orders WHERE user_id = ?';
      const countParams = [parseInt(userId)];
      if (status) {
        countQuery += ' AND status = ?';
        countParams.push(status);
      }
      const [countResult] = await pool.query(countQuery, countParams);
      const total = parseInt(countResult[0].total);

      return {
        data: orders,
        meta: {
          current_page: parseInt(page),
          per_page: parseInt(limit),
          total: total,
          last_page: Math.ceil(total / parseInt(limit))
        }
      };
    } catch (error) {
      console.error(`[OrderModel.getUserOrders] Error fetching orders for userId: ${userId}:`, error);
      throw error;
    }
  }

  // 获取订单详情
  static async getOrderById(orderId, userId) {
    console.log(`[OrderModel.getOrderById] Fetching order ${orderId} for userId: ${userId}`);
    try {
      // 获取订单基本信息
      const [orders] = await pool.execute(
        `SELECT o.*, 
          sa.recipient_name, sa.phone_number, sa.street_address, 
          sa.city, sa.district, sa.province, sa.postal_code, sa.country
        FROM orders o
        LEFT JOIN user_addresses sa ON o.shipping_address_id = sa.id
        WHERE o.id = ? AND o.user_id = ?`,
        [orderId, userId]
      );

      if (orders.length === 0) {
        throw new NotFoundError('订单不存在或不属于当前用户');
      }

      const order = orders[0];

      // 获取订单项
      const [items] = await pool.execute(
        `SELECT * FROM order_items WHERE order_id = ?`,
        [orderId]
      );

      order.items = items;

      // 获取订单状态历史
      const [statusHistory] = await pool.execute(
        `SELECT * FROM order_status_history 
        WHERE order_id = ? 
        ORDER BY changed_at DESC`,
        [orderId]
      );

      order.status_history = statusHistory;

      return order;
    } catch (error) {
      console.error(`[OrderModel.getOrderById] Error fetching order ${orderId} for userId: ${userId}:`, error);
      throw error;
    }
  }

  // 取消订单
  static async cancelOrder(orderId, userId) {
    console.log(`[OrderModel.cancelOrder] Cancelling order ${orderId} for userId: ${userId}`);
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 检查订单是否存在且属于当前用户
      const [orders] = await connection.execute(
        'SELECT * FROM orders WHERE id = ? AND user_id = ?',
        [orderId, userId]
      );

      if (orders.length === 0) {
        throw new NotFoundError('订单不存在或不属于当前用户');
      }

      const order = orders[0];

      // 检查订单状态是否可以取消
      if (!['pending_payment', 'processing'].includes(order.status)) {
        throw new ValidationError('订单状态不允许取消');
      }

      // 更新订单状态
      await connection.execute(
        'UPDATE orders SET status = ?, cancelled_at = NOW(), updated_at = NOW() WHERE id = ?',
        ['cancelled', orderId]
      );

      // 记录状态变更历史
      await connection.execute(
        `INSERT INTO order_status_history (
          order_id, 
          status, 
          notes, 
          changed_at
        ) VALUES (?, ?, ?, NOW())`,
        [orderId, 'cancelled', '用户取消订单']
      );

      await connection.commit();

      // 获取更新后的订单信息
      return this.getOrderById(orderId, userId);
    } catch (error) {
      await connection.rollback();
      console.error(`[OrderModel.cancelOrder] Error cancelling order ${orderId} for userId: ${userId}:`, error);
      throw error;
    } finally {
      connection.release();
    }
  }

  // 更新订单状态
  static async updateOrderStatus(orderNumber, userId, newStatus, notes = null) {
    // 验证订单存在且属于该用户
    const [orders] = await pool.execute(
      'SELECT id, status FROM orders WHERE order_number = ? AND user_id = ?',
      [orderNumber, userId]
    );

    if (orders.length === 0) {
      throw new NotFoundError('订单不存在');
    }

    const order = orders[0];
    const allowedStatusTransitions = {
      'processing': ['cancelled'],
      'shipped': ['completed', 'cancelled'],
      'completed': [],
      'cancelled': [],
      'pending_payment': ['processing', 'cancelled']
    };

    // 验证状态转换是否允许
    if (!allowedStatusTransitions[order.status]?.includes(newStatus)) {
      throw new ValidationError('非法的状态转换', {
        status: [`不能从 ${order.status} 转换到 ${newStatus}`]
      });
    }

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 更新订单状态
      await connection.execute(
        `UPDATE orders 
        SET 
          status = ?,
          ${newStatus}_at = CURRENT_TIMESTAMP,
          updated_at = CURRENT_TIMESTAMP
        WHERE order_number = ?`,
        [newStatus, orderNumber]
      );

      // 记录状态变更历史
      await connection.execute(
        `INSERT INTO order_status_history (
          order_id, status, notes, changed_by_user_id
        ) VALUES (?, ?, ?, ?)`,
        [order.id, newStatus, notes, userId]
      );

      // 如果取消订单，恢复商品库存
      if (newStatus === 'cancelled') {
        const [items] = await connection.execute(
          'SELECT product_id, quantity FROM order_items WHERE order_id = ?',
          [order.id]
        );

        for (const item of items) {
          await connection.execute(
            'UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?',
            [item.quantity, item.product_id]
          );
        }
      }

      await connection.commit();
      return await this.getOrderByNumber(orderNumber);

    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  // 通过订单号获取订单详情
  static async getOrderByNumber(orderNumber, userId) {
    console.log(`[OrderModel.getOrderByNumber] Fetching order ${orderNumber} for userId: ${userId}`);
    try {
      // 获取订单基本信息
      const [orders] = await pool.execute(
        `SELECT o.*, 
          sa.recipient_name, sa.phone_number, sa.street_address, 
          sa.city, sa.district, sa.province, sa.postal_code, sa.country
        FROM orders o
        LEFT JOIN user_addresses sa ON o.shipping_address_id = sa.id
        WHERE o.order_number = ? AND o.user_id = ?`,
        [orderNumber, userId]
      );

      if (orders.length === 0) {
        throw new NotFoundError('订单不存在或不属于当前用户');
      }

      const order = orders[0];

      // 获取订单项
      const [items] = await pool.execute(
        `SELECT * FROM order_items WHERE order_id = ?`,
        [order.id]
      );

      order.items = items;

      // 获取订单状态历史
      const [statusHistory] = await pool.execute(
        `SELECT * FROM order_status_history 
        WHERE order_id = ? 
        ORDER BY changed_at DESC`,
        [order.id]
      );

      order.status_history = statusHistory;

      return order;
    } catch (error) {
      console.error(`[OrderModel.getOrderByNumber] Error fetching order ${orderNumber} for userId: ${userId}:`, error);
      throw error;
    }
  }
}

module.exports = OrderModel; 